import {
  hint,
  onlyChangeRouter,
  onlyChangeComplete,
  whetherLogin,
} from "../../utils/util";
import User from "../../models/user";
import Dialog from "@vant/weapp/dialog/dialog";

const user = new User();
const app = getApp();
Page({
  /**
   * 页面的初始数据
   */
  data: {
    baseImgUrl: "",
    user: {},
    houseList: [],
    currentBannerIndex: 0,
    exitFlag: false,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {},

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {},

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    var { baseImgUrl } = getApp().globalImgUrl.config;
    this.setData({
      baseImgUrl,
      exitFlag: wx.getStorageSync("token") ? true : false,
    });

    this.getTabBar().init();
    this.initPageData();
  },
  onlyChangeRouter,
  onlyChangeComplete,
  whetherLogin,
  listHandle(e) {
    let token = wx.getStorageSync("token");
    if (!token) {
      this.setData({
        exitFlag: token ? true : false,
      });
      this.whetherLogin(token);
      return;
    }

    this.onlyChangeRouter(e);
  },
  logout() {
    Dialog.confirm({
      title: "退出提醒",
      zIndex: 10000,
      closeOnClickOverlay: true,
      message: "确认要退出登录吗？",
    })
      .then(() => {
        user
          .logout()
          .then((res) => {
            if (res.success) {
              wx.clearStorage({
                success: () => {
                  setTimeout(() => {
                    hint("退出成功");
                  }, 500);
                  wx.reLaunch({
                    url: "/pages/home/index",
                  });
                },
                fail: () => {
                  hint("退出失败");
                },
              });
            }
          })
          .catch((err) => {
            console.log(err);
          });
      })
      .catch(() => {
        // on cancel
      });
  },
  bannerChange: function (e) {
    let current = e.detail.current;
    this.setData({
      currentBannerIndex: current,
    });
  },
  initPageData() {
    let memberId = wx.getStorageSync("user").memberId;
    if (!memberId) {
      return;
    }

    user
      .centerCellSelection()
      .then((res) => {
        this.setData({
          user: res.result.miniUser,
        });
      })
      .catch((err) => {
        console.log(err);
      });
  },
  onShareAppMessage: function () {
    return {
      title: "标准化智慧社区", //转发的标题。当前小程序名称
      path: `/pages/home/index`, //转发的路径
      imageUrl: "../../static/icon/share.jpg", //自定义图片路径 支持PNG及JPG。显示图片长宽比是 5:4。
    };
  },
});
